package com.hs.room.repository

import android.content.Context
import com.hs.room.AppDatabase
import com.hs.room.model.archive.Archive
import com.hs.room.model.archive.Case
import com.hs.room.repository.service.IArchiveRepository
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flow
import javax.inject.Inject

/**
 * 档案字典仓库 类型、级别、状态
 */
class ArchiveRepository @Inject constructor(
    @ApplicationContext var context: Context,
    val db: AppDatabase
) : IArchiveRepository {

    override suspend fun insert(d: Archive) {
        db.archiveDao().insert(d)
    }

    override suspend fun insert(d: Case) {
        db.caseDao().insert(d)
    }

    override suspend fun update(d: Archive) {
        db.archiveDao().update(d)
    }

    override suspend fun update(d: Case) {
        db.caseDao().update(d)
    }

    override fun getCase(limit: Int, offset: Int): Flow<List<Case>> {
        return flow {
            emitAll(db.caseDao().get(offset, offset * limit))
        }.catch { e ->
            // 进行异常处理
            println("Error occurred while fetching getType data: $e")
        }
    }

    override fun getArchive(limit: Int, offset: Int): Flow<List<Archive>> {
        return flow {
            emitAll(db.archiveDao().get(offset, offset * limit))
        }.catch { e ->
            // 进行异常处理
            println("Error occurred while fetching getType data: $e")
        }
    }

    override fun countCase(): Int {
        return db.caseDao().count()
    }

    override fun countArchive(): Int {
        return db.archiveDao().count()
    }

    override suspend fun delete(d: Case) {
        db.caseDao().delete(d)
    }

    override suspend fun delete(d: Archive) {
        db.archiveDao().delete(d)
    }
}